<?php 	
		require_once("../_inc/sessions.php"); 
		require_once("../_inc/functions.php");
		require_once("../_inc/form_functions.php");
		require_once("../_inc/connection.php");
		
		date_default_timezone_set('Asia/Bangkok');

		if ($_SERVER['HTTP_HOST']==$_SERVER['SERVER_NAME']) {
			
			$errors = array();
			// perform validations on the form data limit to 30 charector
			$required_fields = array('login', 'password',);
			$errors = array_merge($errors, check_required_fields($required_fields, $_POST));

			$fields_with_lengths = array('login' => 40, 'password' => 20);
			$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));

			$proceed = false;
			$expire = false;
			$seconds = 60*30; // set expire 600 Second is mean 10 minute

			if(isset($_POST['ts']) && isset($_COOKIE['token']) && $_COOKIE['token'] == md5('youpassphase'.$_POST['ts'])) {
				$proceed = true;
			}

			// if(!$proceed) { 
			// 	echo 'Form processing halted for suspicious activity';
			// }

			if(((int)$_POST['ts'] + $seconds) < mktime()) {
				// echo 'Too much time elapsed';
				$expire = true;
			}

			if ( !$proceed || $expire) {
				$data['expire'] = "1";	// cookie expire
			}else {
				if ( empty($errors) ) {

					$login = trim(mysql_prep(htmlentities($_POST['login'])));
					$password = trim(mysql_prep(htmlentities($_POST['password'])));
					$hashed_password = sha1($password);
					// Check database to see if username and the hashed password exist there.
					$query = "SELECT `id`,`staff`";
					$query .= " FROM user";
					// $query .= " WHERE (user = '{$login}' OR email = '{$login}')";
					$query .= " WHERE user = '{$login}'";
					$query .= " AND hpwd = '{$hashed_password}'";
					$query .= " AND visible = 1";
					$query .= " LIMIT 1";
					mysql_query("SET NAMES 'utf8'",$connection); 
					$result = mysql_query($query,$connection);
					confirm_query($result);
					if (mysql_num_rows($result) == 1) {						
						$row = mysql_fetch_assoc($result);
						if ($row['staff'] == 1) {
							$_SESSION['staff_id'] = $row['id'];
						}
						// redirect not work with ajax form submit
						$data['success'] = "1";
					}
					else { // didn't found user
						$data['failed'] = "1";
						// $_SESSION['login_failed'] = 1;
						// $ipaddress = $_SERVER['REMOTE_ADDR'];
						// user_track($ipaddress,0,"login_failed=[{$login}]");
						
					}
				}

			}
			echo json_encode($data);
		}

		mysql_close($connection);
?>